import time
from pages.excel_data_extraction import Excel_data_extraction
from config.settings import get_config
from base.base_page import BasePage

"""
封装功能函数

"""
class Remote_Operation_Manage(BasePage):
    def __init__(self, driver, device_type, logger=None):
        super().__init__(driver, device_type, logger=logger)  # 传递日志实例
        self.driver = driver
        self.config = get_config(device_type)  # 获取全局配置
        self.excel_processor = Excel_data_extraction(self.driver, device_type, logger=logger)

    def ssh_up_down(self, ssh_status, automatic_down_time):
        self.enter_remote_operation_manage()
        self.update_ssh_status(ssh_status='停止')
        self.save_ssh_status()
        self.update_ssh_status(ssh_status)
        self.ssh_automatic_down(automatic_down_time)
        self.save_ssh_status()

    def enter_remote_operation_manage(self):
        # 进入远程运维管理界面
        if self.quick_check_element('remote_operation_manage', 'ssh_up_down'):
            pass
        else:
            self.click('first_level_menu_module', 'remote_operation_manage')
            self.soft_assert_element_visible('remote_operation_manage', 'ssh_up_down')


    def update_ssh_status(self, ssh_status):
        """ 修改状态 """
        self.enter_remote_operation_manage()
        result =  self.find_element('remote_operation_manage', 'ssh_up_down')
        if result is None:
            pass
        else:
            if "ivu-switch-checked" in result.get_attribute("class"):
                if ssh_status == '启动':
                    pass
                else:
                    self.click('remote_operation_manage', 'ssh_up_down')
            else:
                if ssh_status == '停止':
                    pass
                else:
                    self.click('remote_operation_manage', 'ssh_up_down')

    def ssh_automatic_down(self, automatic_down_time):
        # ssh自动关闭时间设置
        if automatic_down_time == '':
            pass
        else:
            self.click('remote_operation_manage', 'ssh_automatic_down')
            selected_result = self.select_interface_options(
                element_locator='ssh_automatic_down_all',
                values=automatic_down_time,
                param_name='automatic_down_time'
            )
            self.soft_assert_text_equal('remote_operation_manage', 'ssh_automatic_down', automatic_down_time)
            return selected_result


    def save_ssh_status(self):
        """ 保存数据接口 """
        self.click('remote_operation_manage', 'save_ssh_configure')
        self.click('common_elements', 'confirm_button')
        if self.find_element('common_elements', 'update_success'):
            self.logger.info(f'SSH状态修改成功')
        else:
            self.logger.error(f'SSH状态修改失败')
        time.sleep(2)

    def query_paged_data(self, search_locator: str, target_locator: str, value: str, param_name: str):
        """通用分页数据查询方法（返回符合的元素、单值）"""
        # 标准化输入值
        target_text = str(value).strip()
        current_page = 1

        while True:
            # 获取当前页所有可选项
            options = self.find_elements('remote_operation_manage', search_locator)

            # 遍历匹配选项
            for row_index, element in enumerate(options, 1):
                option_text = element.text.strip()
                if option_text == target_text:
                    # 获取同行的目标元素
                    target_element = self.find_dynamic_element(
                        'remote_operation_manage',
                        target_locator,
                        row_index
                    )
                    return target_element  # 直接返回元素
                    # return target_element.text.strip() #直接返回字符串

            # 尝试翻页
            if not self._go_to_next_page():
                self.logger.debug(f"未找到匹配项: {target_text}，已遍历 {current_page} 页")
                return None  # 静默返回None

            current_page += 1

    def select_interface_options(self, element_locator: str, values: list, param_name: str):
        """通用接口选项选择方法（基础方法）"""
        # 类型统一处理
        if not isinstance(values, list):
            values = [values]

        selected = []
        for value in values:
            # 获取所有可选项
            options = self.find_elements('remote_operation_manage', element_locator)

            # 标准化输入值
            target_text = str(value).strip()

            # 遍历匹配选项
            found = False
            for option in options:
                option_text = option.text.strip()
                if option_text == target_text:
                    self.highlight_element(option)  # 可视化点击元素
                    option.click()
                    selected.append(option_text)
                    found = True
                    break

            if not found:
                available_options = [opt.text.strip() for opt in options]
                raise ValueError(
                    f"参数 {param_name} 未找到选项: '{target_text}'\n"
                    f"可用选项: {available_options}"
                )
            return selected
